package com.ray.woodencreate.aspect;

import com.alibaba.fastjson.JSON;
import com.ray.woodencreate.logs.SystemLogBuilder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @author bo shen
 * @Description: 性能监控切面
 * @Class: PerformanceAspect
 * @Package com.toptoday.woodencreate.aspect
 * @date 2018/10/10 18:02
 * @company <p>Ray快速开发平台</p>
 * @updateRecord time(修改时间)  author(修改人)   desc(修改内容)
 */
@Aspect
@Component
@Slf4j
@Order(1002)
public class ServiceLogAspect {


    /**
     * 统一性能处理
     */
    @Pointcut("@annotation(com.ray.woodencreate.annotation.ServiceLog)")
    public void serviceLog(){

    }

    /**
     * @param joinPoint
     * @throws Throwable
     */
    @Before("serviceLog()")
    public void start(JoinPoint joinPoint) throws Throwable {
        List<Object> args = new ArrayList<>();
        for(Object object : joinPoint.getArgs()){
          if(isParams(object)){
              args.add(object);
          }
        }
        String body = String.format("进入方法-请求方法[%s.%s],参数:%s",joinPoint.getSignature().getDeclaringTypeName(),joinPoint.getSignature().getName()
        , JSON.toJSON(args));
        log.info(new SystemLogBuilder().appendLevelTips().appendMsg(body).bulidString());
    }

    @AfterReturning(returning = "ret", pointcut = "serviceLog()")
    public void end(JoinPoint joinPoint,Object ret) throws Throwable {
        log.info(new SystemLogBuilder().appendLevelTips().appendMsg("方法执行结束.").bulidString());
    }

    private boolean isParams(Object object) {
        return !(object instanceof HttpServletRequest
                ||object instanceof HttpServletRequest);
    }

}
